# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''应用程序配置

说明:
    1. 为应用程序加入库目录支持
    2. 为应用程序加入配置

历史:
    2018-10-26 姚彧 创建
'''

__all__ = ['AppConfig']

import os
import sys
import configparser
from tool.Singleton import MetaSingleton
from version import AppEnviron


class AppConfig(object, metaclass = MetaSingleton):
    __config = None
    def __init__(self):
        inifile = os.path.join(AppEnviron.get_app_path(), 'config.ini')
        assert os.path.isfile(inifile), inifile
        config = configparser.ConfigParser()
        config.readfp(open(inifile))
        self.__config = config
        self.__section = "%s.python3" % self.get_platform()
        self.sys_add_paths(self.attr('yypylib', '').split(';'))

    def attr(self, key, default = None):
        if self.__config:
            return self.__config.get(self.__section, key, fallback = default)
        else:
            return os.environ.get(key, default)

    @staticmethod
    def get_platform():
        platform_dict = {'win32': 'win',}
        return platform_dict.get(sys.platform, 'other')

    @staticmethod
    def sys_add_paths(paths):
        for path in paths:
            path = os.path.abspath(path)
            if os.path.isdir(path) and path not in sys.path:
                print('Add to sys.path: %s' % path)
                sys.path.append(path)
